<?php
namespace app\api\controller;

use app\api\consDir\ErrorConst;
use app\api\logic\ShopLogic;
use app\common\controller\RestController;
use app\common\utils\CommonUtil;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class Shop extends RestController
{
    protected $noNeedLogin = [
        'addComment',
        'shopPic',
        'shopInfo',
        'shopDetail',
        'shopComment',
        'shopList',
        'shopCategory',
    ];

    public function addComment(): bool
    {
        $shopId           = input('shopId', 0);
        $imgContent       = input('imgContent', '');
        $serveScore       = input('serveScore', 5);
        $environmentScore = input('environmentScore', 5);
        $costScore        = input('costScore', 5);
        $content          = input('content', '默认评论');
        $orderNo          = input('orderNo', '');
        $isAnonymity      = input('isAnonymity', 0);

        $info = ShopLogic::getInstance()->addComment(
            $shopId,
            $imgContent,
            $serveScore,
            $environmentScore,
            $costScore,
            $content,
            $orderNo,
            $isAnonymity);
        return $this->result($info);
    }

    public function shopPic(): bool
    {
        $shopId = input('shopId', 0);
        $typeId = input('typeId', 0);
        $info   = ShopLogic::getInstance()->shopPic($shopId, $typeId);
        return $this->result($info);
    }

    /**
     * @return bool
     */
    public function shopInfo(): bool
    {
        $shopId = input('shopId', 0);
        $info   = ShopLogic::getInstance()->shopInfo($shopId);
        if ( ! empty($info)) {
            // 累计店铺浏览量
            \think\facade\Db::table('member_shop')
                ->where('id', $shopId)
                ->inc('view_count')
                ->update();
        }

        return $this->result($info);
    }

    public function checkShopStatus()
    {
        $info = ShopLogic::getInstance()->shopInfoByUid();
        // $info       = [];
        $shopBanner = empty($info['shopBanner']) ? [] : str2arr($info['shopBanner']);
        if ( ! empty($shopBanner)) {
            $shopBanner2 = [];
            foreach ($shopBanner as $url) {
                $shopBanner2[] = ['url' => $url];
            }
            $info['shopBanners'] = $shopBanner2;
        } else {
            $info['shopBanners'] = [];
        }

        $info['corporateIdBacks'] = empty($info['corporateIdBack']) ? [] : [
            ['url' => $info['corporateIdBack']],
        ];
        $info['corporateIdFronts'] = empty($info['corporateIdFront']) ? [] : [
            ['url' => $info['corporateIdFront']],
        ];

        $info['shopLogos'] = empty($info['shopLogo']) ? [] : [
            ['url' => $info['shopLogo']],
        ];
        $info['shopBusinessImgs'] = empty($info['shopBusinessImg']) ? [] : [
            ['url' => $info['shopBusinessImg']],
        ];
        // 0 审核中 1 成功 2 拒绝 -1 未申请
        $info['status'] = $info['status'] ?? -1;
        // var_dump($status, $info['authRemark']);exit;
        if ($info['status'] == 2 && ! empty($info['authRemark'])) {
            $info['authRemark'] = "您的入驻申请被管理员驳回，主要原因是：" . $info['authRemark'];
        }
        return $this->result($info);
    }

    /**
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function shopDetail(): bool
    {
        $shopId = input('shopId', 0);
        $type   = input('type', 0); // 修改店铺则传1
        // var_dump(app()->userinfo->id);exit;
        if ($type == 0) {
            $info = ShopLogic::getInstance()->shopDetail([
                'id' => $shopId,
            ]);
        } else {
            $info = ShopLogic::getInstance()->shopDetailAll([
                'id' => $shopId,
            ]);
        }
        if ( ! empty($info)) {
            // 累计店铺浏览量
            \think\facade\Db::table('member_shop')
                ->where('id', $shopId)
                ->inc('view_count')
                ->update();
        }
        return $this->result($info);
    }

    /**
     * 仅供店主查看店铺信息用
     * @return [type] [description]
     */
    public function myShop(): bool
    {
        // var_dump(app()->userinfo->id);exit;
        $info = ShopLogic::getInstance()->shopDetail([
            'user_id' => app()->userinfo->id,
        ]);
        return $this->result($info);
    }

    /**
     * 店铺评论列表
     * @return bool
     */
    public function shopComment(): bool
    {
        $shopId   = input('shopId', 0);
        $page     = input('page', 1);
        $pageSize = input('pageSize', 10);
        $isBad    = input('isBad', 0);
        $isImg    = input('isImg', 0);
        $info     = ShopLogic::getInstance()->shopComment($shopId, $page, $pageSize, $isBad, $isImg);
        return $this->result($info);
    }

    /**
     * @return bool
     */
    public function shopList(): bool
    {
        //$lat,$lng
        $city       = input('city', '');
        $page       = input('page', 1);
        $pageSize   = input('pageSize', 10);
        $shopType   = input('shopType', 1);
        $lat        = input('lat', 0);
        $lng        = input('lng', 0);
        $sort       = input('sort', 0);
        $keyword    = input('keyword', '');
        $categoryId = input('categoryId', 0);
        $isHot      = input('isHot', null);
        $isBrand    = input('isBrand', null);
        $isVillage  = input('isVillage', null);
        $minPer     = input('minPer', null);
        $maxPer     = input('maxPer', null);
        $isWifi     = input('isWifi', null); // 是否有WiFi
        $isStop     = input('isStop', null); // 是否免费停车
        $isBox      = input('isBox', null); // 是否有包厢
        $isBattery  = input('isBattery', null); // 是否有充电宝
        $km         = input('km', 0);

        // 筛选-综合排序
        $comprehensive = input('comprehensive', '');
        if ( ! empty($comprehensive) && is_string($comprehensive)) { // 支持单选
            $$comprehensive = 1;
        } elseif ( ! empty($comprehensive) && is_array($comprehensive)) { // 支持多选
            foreach ($comprehensive as $item) {
                $$item = 1;
            }
        }

        $price = input('price', '');
        $price = explode('-', $price);
        if (count($price) == 2) {
            $minPer = (int) $price[0];
            $maxPer = (int) $price[1];
        }
        $info = ShopLogic::getInstance()->shopList(
            $shopType
            , $page
            , $pageSize
            , $sort
            , $lat
            , $lng
            , $keyword
            , $categoryId
            , $city
            , $isHot
            , $isBrand
            , $isVillage
            , $minPer
            , $maxPer
            , $isWifi
            , $isStop
            , $isBox
            , $isBattery
            , $km);
        return $this->result($info);
    }

    public function shopCategory(): bool
    {
        // $online 1 线上  0 线下（非1）
        $online = input('online', 0);
        $info   = ShopLogic::getInstance()->shopCategory($online);
        array_unshift($info['rows'], [
            'id'    => '',
            'title' => '全部',
            'icon'  => 'https://rx-files.rxx1316.com/202405/25105608-23290159765027700.png',
        ]);
        return $this->result([
            'rows'          => $info['rows'],
            'km'            => [
                ['id' => '', 'title' => '不限'],
                ['id' => '1000', 'title' => '1km'],
                ['id' => '3000', 'title' => '3km'],
                ['id' => '5000', 'title' => '5km'],
                ['id' => '10000', 'title' => '10km'],
            ],
            'price'         => [
                ['id' => '0 - 50', 'title' => '50以下'],
                ['id' => '50 - 100', 'title' => '50 - 100以下'],
                ['id' => '100 - 300', 'title' => '100 - 300以下'],
                ['id' => '300 - 500', 'title' => '300 - 500以下'],
                ['id' => '500 - 0', 'title' => '500以上'],
            ],
            'sort'          => [ // 综合排序
                // 综合排序 id 设置为 空字符串 和前端约定
                ['id' => '', 'title' => '综合排序'],
                ['id' => '1', 'title' => '人均从高到低'],
                ['id' => '2', 'title' => '人均从低到高'],
                ['id' => '5', 'title' => '人气优先'],
                ['id' => '4', 'title' => '离我最近'],
            ],
            'comprehensive' => [ // 筛选-综合排序
                ['id' => 'isHot', 'title' => '热门'],
                ['id' => 'isBrand', 'title' => '品牌'],
                ['id' => 'isWifi', 'title' => '免费WiFi'],
                ['id' => 'isStop', 'title' => '免费停车'],
                ['id' => 'isBox', 'title' => '有包厢'],
                ['id' => 'isBattery', 'title' => '有充电宝'],
            ],
        ]);
    }

    /**
     * 店铺申请前查询数据
     */
    public function applyBefore()
    {
        $marks1 = \think\facade\Db::table('member_shop_mark')
            ->where('business_type', 1)
            ->where('status', 1)
            ->order('sort desc, id desc')
            ->column('name');
        $marks2 = \think\facade\Db::table('member_shop_mark')
            ->where('business_type', 2)
            ->where('status', 1)
            ->order('sort desc, id desc')
            ->column('name');
        $marks3 = \think\facade\Db::table('member_shop_mark')
            ->where('business_type', 3)
            ->where('status', 1)
            ->order('sort desc, id desc')
            ->column('name');

        $platformFeeMin = (int) sysconf('platform_fee_min');
        $platformFeeMax = (int) sysconf('platform_fee_max');
        if (is_numeric($platformFeeMin) == false && empty($platformFeeMin)) {
            $platformFeeMin = 5;
        }
        if (empty($platformFeeMax)) {
            $platformFeeMax = 90;
        }
        return $this->result([
            // businessType 商家类型: 1 个体工商户  2 企业  3 小微商家
            'platformFeeMin' => $platformFeeMin, // 服务费比例  让利比例 min
            'platformFeeMax' => $platformFeeMax, // 服务费比例  让利比例 max
            'marks'          => [
                'marks1' => $marks1,
                'marks2' => $marks2,
                'marks3' => $marks3,
            ], // 商户标签
            'openWeek'       => ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
            'items'          => [
                [
                    'businessType' => 1,
                    'title'        => '个体工商户',
                    'desc'         => '适用于营业执照名称或类型包含个体工商户、个人独资企业的公司',
                    'icon'         => '', // 如果不为空，前端就会使用它
                    'subtitle'     => '我需要准备什么材料？',
                    'popupTitle'   => '个体户主体认证说明',
                    'popupBody'    => "需准备好如下资料:<br/>1:营业执照照片(必须是清晰的)<br/>2:营业执照的名称<br/>3:营业执照地址<br/>4:营业执照码<br/>5:营业执照的经营范围<br/>6:组成形式(指令个人经营或家庭经营)<br/>7:银行卡信息",
                ],
                [
                    'businessType' => 2,
                    'title'        => '企业',
                    'desc'         => '适用于营业执照名称或类型包含有限责任公司、股份有限公司',
                    'icon'         => '', // 如果不为空，前端就会使用它
                    'subtitle'     => '我需要准备什么材料？',
                    'popupTitle'   => '企业主体认证说明',
                    'popupBody'    => "需准备好如下资料:<br/>1:营业执照照片(必须是清晰的)<br/>2:营业执照的名称<br/>3:营业执照地址<br/>4:营业执照编码<br/>5:营业执照的经营范围<br/>6:营业执照注册资本<br/>7:对公账户卡号以及开户行信息<br/>8:法人信息(身份证正反面、身份证号码)<br/>9:邮箱地址",
                ],
                [
                    'businessType' => 3,
                    'title'        => '小微商家',
                    'desc'         => '无需营业执照，以个体财产或家庭财产为经营资本',
                    'icon'         => '', // 如果不为空，前端就会使用它
                    'subtitle'     => '我需要准备什么材料？',
                    'popupTitle'   => '小微商家',
                    'popupBody'    => "需准备好如下资料:<br/>1:个人信息(身份证正反面、身份证号码)<br/>2:银行卡",
                ],
            ],
        ]);
    }

    /**
     * 店铺申请接口
     */
    public function addShop()
    {
        $data['shop_logo']         = input('shopLogo', '');
        $data['shop_name']         = input('shopName', '');
        $data['shop_type']         = input('shopType', 0);
        $data['province']          = input('province', '');
        $data['province_id']       = input('provinceId', 0);
        $data['city']              = input('city', '');
        $data['city_id']           = input('cityId', 0);
        $data['country']           = input('country', '');
        $data['country_id']        = input('countryId', 0);
        $data['street']            = input('street', '');
        $data['street_id']         = input('streetId', 0);
        $data['comm']              = input('comm', '');
        $data['comm_id']           = input('commId', 0);
        $data['latitude']          = input('latitude', '');
        $data['longitude']         = input('longitude', '');
        $data['address']           = input('address', '');
        $data['contract']          = input('contract', '');
        $data['category_id']       = input('categoryId', 0);
        $data['shop_no']           = input('shopNo', '');
        $data['shop_idc']          = input('shopIdc', '');
        $data['real_name']         = input('realName', '');
        $data['platform_fee']      = input('platformFee', '');
        $data['shop_business_img'] = input('shopBusinessImg', '');
        $data['shop_type']         = input('shopType', '');
        $data['admin_account']     = input('userName', '');
        $data['shop_phone']        = input('shopPhone', ''); // 联系方式
        // 商家类型: 1 个体工商户  2 企业  3 小微商家
        $data['business_type'] = input('businessType', 0);
        $data['business_name'] = input('businessName', '');
        $data['content']       = input('content', ''); // 商户简介/店铺描述

        if($data['shop_type'] == 1){
            if(empty($data['latitude']) || empty($data['longitude'])){
                CommonUtil::throwException(ErrorConst::PARAM_ERROR, '经纬度不能为空');
            }
        }

        $openWeek = input('openWeek', '');
        if ( ! empty($openWeek)) {
            $data['open_week'] = is_array($openWeek) ? json_encode($openWeek, 320) : $openWeek;
        }
        // 门头照片
        $data['shop_banner'] = input('shopBanner', '');

        $bankCardInfo = input('bankCardInfo', '');
        if ( ! empty($bankCardInfo)) {
            $data['bank_card_info'] = is_array($bankCardInfo) ? json_encode($bankCardInfo, 320) : $bankCardInfo;
        }

        $marks = input('marks', '');
        if ( ! empty($marks)) {
            $data['marks'] = is_array($marks) ? arr2str($marks) : $marks;
        }

         ! empty(input('openTimeStart')) && $data['open_time_start'] = input('openTimeStart', '');
         ! empty(input('openTimeEnd')) && $data['open_time_end']     = input('openTimeEnd', '');
         ! empty(input('businessScope')) && $data['business_scope']  = input('businessScope', '');

         ! empty(input('wechat')) && $data['wechat']                       = input('wechat', '');
         ! empty(input('alipay')) && $data['alipay']                       = input('alipay', '');
         ! empty(input('sysIm')) && $data['sys_im']                        = input('sysIm', '');
         ! empty(input('adminAccount')) && $data['admin_account']          = input('adminAccount', '');
         ! empty(input('corporateId')) && $data['corporate_id']            = input('corporateId', '');
         ! empty(input('corporateIdFront')) && $data['corporate_id_front'] = input('corporateIdFront', '');
         ! empty(input('corporateIdBack')) && $data['corporate_id_back']   = input('corporateIdBack', '');

        $pwd = input('userPassword', '');

        $id = input('shopId');
        if (empty($id)) {
            $data['admin_pwd'] = empty($pwd) ? '' : md5($pwd);
            //设置管理员
            //在审核通过的时候生成管理员记录
            $info = ShopLogic::getInstance()->apply($data);
        } else {
            $status = \think\facade\Db::table('member_shop_apply')
                ->where('deleted', 0)
                ->where('id', $id)
                ->value('status');
            // 0 审核中 1 成功 2 拒绝
            if ($status == 1) {
                \app\common\utils\CommonUtil::throwException(
                    \app\api\consDir\ErrorConst::PARAM_ERROR,
                    '已经审核通过，不允许修改资料',
                );
            }
            $data['status'] = 0;

             ! empty($pwd) && $data['admin_pwd'] = md5($pwd);
            \think\facade\Db::table('member_shop_apply')
                ->where('deleted', 0)
                ->where('id', $id)
                ->update($data);
            $info = [
                'code'        => 0,
                'msg'         => 'success',
                'status'      => 0,
                'id'          => $id,
                'auth_at'     => '',
                'auth_remark' => '',
            ];
        }
        return $this->result($info);
    }
}
